package com.angcyo.selenium.auto.action

import com.angcyo.javafx.base.ex.onBack
import com.angcyo.library.ex.patternList
import com.angcyo.library.file.fileName
import com.angcyo.selenium.PairOutputType
import com.angcyo.selenium.auto.BaseControl
import com.angcyo.selenium.auto.parse.HandleResult
import com.angcyo.selenium.auto.parse.args
import com.angcyo.selenium.bean.ActionBean
import com.angcyo.selenium.bean.putMap
import org.openqa.selenium.WebElement

/**
 * Email:angcyo@126.com
 * @author angcyo
 * @date 2020/12/31
 */
class GetAttrAction : BaseAction() {

    override fun interceptAction(control: BaseControl, action: String?): Boolean {
        return action?.startsWith(Action.ACTION_GET_ATTR) == true
    }

    override fun runAction(
        control: BaseControl,
        element: WebElement,
        actionBean: ActionBean,
        action: String
    ): HandleResult {
        val result = HandleResult()
        result.elementList = listOf(element)

        var key: String? = "getAttr"
        action.args { index, arg ->
            if (index == 1) {
                key = arg
            }
        }

        //读取[xxx] xxx属性名
        val attrName = action.patternList("(?<=\\[).+(?=\\])").firstOrNull()

        val text: String?
        if (!attrName.isNullOrEmpty()) {
            text = element.getAttribute(attrName)

            //保存起来
            if (!key.isNullOrEmpty()) {
                control._currentTaskBean?.putMap(key, text)
            }

            result.success = text != null
        } else {
            text = null
        }

        //log
        if (result.success) {
            if (text?.startsWith(Action.base64Image) == true) {
                val removeBase64Image = text.removeBase64Image()

                //保存验证码图片
                onBack {
                    PairOutputType().apply {
                        fileName = fileName(suffix = "_${attrName}.png")
                        convertFromBase64Png(removeBase64Image)?.let {
                            try {
                                ScreenshotAction.screenshotAction?.invoke(it.second, null, null)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                }
            }
        }

        control.logAction?.invoke("获取属性[$attrName]=[$text]:${result.success}")
        return result
    }
}